<template>
  <el-card style="margin:20px;height: 70px;">
    <el-form :inline="true">
    <el-form-item>
      <el-select v-model="searchFrom.subjectName"
                 clearable
                 filterable
                 style="width:240px;"
                 placeholder="请输入专题名称">
        <el-option
            v-for="item in tableData"
            :label="item.subjectName"
            :value="item.subjectName">
        </el-option>
      </el-select>
    </el-form-item>
      <el-form-item>
        <el-button @click="resetSearch">重置</el-button>
        <el-button type="primary" @click="search">搜索</el-button>
      </el-form-item>
    </el-form>
  </el-card>

  <el-card style="margin:20px;">
    <div style="margin:10px 0 40px 10px;">
      专题列表
      <el-button type="success" style="float: right;margin-top:-3px;" @click="addSubject">新增专题</el-button>
    </div>
    <el-table :data="paginatedData"
              style="height: 465px">>
      <el-table-column type="index" label="编号" width="80" align="center"/>
      <el-table-column prop="subjectName" label="专题名称" align="center"/>
      <el-table-column prop="description" label="专题描述" align="center"/>
      <el-table-column prop="createTime" label="创建时间" align="center"/>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button link type="primary"
                     @click="editSubject(scope.row.id)">编辑
          </el-button>
          <el-button link type="danger"
                     @click="deleteSubject(scope.row.id)">删除
          </el-button>
          <el-button link type="primary"
                     @click="findAll(scope.row.id)">
            详情内容<el-icon><MoreFilled /></el-icon>
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        v-model:current-page="currentPage"
        :page-size="pageSize"
        layout="total, prev, pager, next, jumper"
        :total="tableData.length"
        @current-change="handlePageChange"
        style="margin-top:20px;margin-left:  35%"
    />

  </el-card>


  <el-dialog :title="subjectTitle"
             v-model="subjectVisible"
             style="width:600px; padding:40px;margin-top: 200px"
             :before-close="handleClose">
    <el-form label-width="80px" label-position="top">
          <el-form-item label="专题名称">
            <el-input placeholder="请输入专题名称"
                      v-model="saveFrom.subjectName"/>
          </el-form-item>

          <el-form-item label="专题简介">
            <el-input
                v-model="saveFrom.description"
                :autosize="{ minRows: 4, maxRows: 4 }"
                maxlength="20"
                show-word-limit
                type="textarea"
                placeholder="请输入相关信息"
            />
          </el-form-item>

             <el-form-item label="专题海报">
               <el-upload
                   v-model:file-list="fileList"
                   v-model:action="actionUrl"
                   name="file"
                   limit="1"
                   list-type="picture-card"
                   :on-preview="handlePictureCardPreview"
                   :on-remove="handleRemove"
               >
                 <el-icon>
                   <Plus/>
                 </el-icon>
               </el-upload>
               <el-dialog v-model="dialogVisible">
                 <img :src="dialogImageUrl"
                      :alt="dialogImageUrl"/>
               </el-dialog>
             </el-form-item>


    </el-form>

    <template #footer>
      <el-button type="danger" @click="handleClose">取消</el-button>
      <el-button type="primary" @click="saveSubject">保存</el-button>
    </template>
  </el-dialog>


</template>


<script setup>
import {computed, onMounted, ref} from "vue";
import qs from "qs";
import {ElMessage, ElMessageBox} from "element-plus";
import axios from "axios";
import router from "@/router";

const tableData = ref([]);
const currentPage = ref(1);// 默认显示页码
const pageSize = ref(10); // 每页显示几条

// 计算当前页面的数据
const paginatedData = computed(() => {
  const offset = (currentPage.value - 1) * pageSize.value;
  return tableData.value.slice(offset, offset + pageSize.value);
});

// 分页变化时触发
const handlePageChange = (newPage) => {
  currentPage.value = newPage;
};
const searchFrom = ref({
  subjectName: '',
});
const search = () => {
  let data = qs.stringify(searchFrom.value);
  axios.get(BASE_URL + '/v1/subject/select?' + data)
      .then((response) => {
        if (response.data.code === 2000) {
          tableData.value = response.data.data;
        } else {
          ElMessage({
            message: response.data.msg,
            type: 'error',
            showClose: true,
            center: true,
          });
        }
      });
}
onMounted(() => {
  search();
})
const resetSearch = () => {
  searchFrom.value = {};
  search();
}
const subjectVisible = ref(false);
const subjectTitle = ref('新增专题');
const saveFrom = ref({
  subjectName: '',
  description: '',
  poster: '',
});
const cleanAll = () => {
  saveFrom.value = {
    subjectName: '',
    description: '',
    poster: '',
  };
  fileList.value = [];
}
/**图片上传相关代码开始**/
const fileList = ref([]);
const dialogImageUrl = ref('');
const dialogVisible = ref(false);
//定义变量用来保存图片上传给哪个后端接口地址
const actionUrl = ref(BASE_URL + '/v1/file/upload');
//移除图片
const handleRemove = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
  //1.得到要删除的图片路径 uploadFile就是我们要删除的那个图片文件对象
  let imgUrl = uploadFile.response.data;
  //2.给后端发请求,删除图片
  axios.post(BASE_URL + '/v1/file/remove?imgUrl=' + imgUrl)
      .then((response) => {
        if (response.data.code === 2000) {
          ElMessage.success('删除成功!');
        }
      })
}
//图片上传后预览
const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url
  dialogVisible.value = true;
}
/**图片上传相关代码结束**/
const addSubject = () => {
  subjectVisible.value = true;
  subjectTitle.value = '新增专题';
}

const saveSubject = () => {
  if (saveFrom.value.subjectName === null || saveFrom.value.subjectName === '') {
    errorInfo('请输入专题名称');
    return;
  }
  if (saveFrom.value.description === null || saveFrom.value.description === '') {
    errorInfo('请输入描述信息');
    return;
  }
  if (fileList.value.length === 0) {
    errorInfo('请上传导演照片');
    return;
  }
  saveFrom.value.poster = fileList.value[0].response.data;
  let data = qs.stringify(saveFrom.value);
  axios.post(BASE_URL + '/v1/subject/save', data)
      .then((response) => {
        if (response.data.code === 2000) {
          OKInfo('保存成功!');
          subjectVisible.value = false;
          cleanAll();
          search();
        } else {
          ElMessage({
            message: response.data.msg,
            type: 'error',
            showClose: true,
            center: true,
          })
        }
      })


}
const handleClose = () => {
  ElMessageBox.confirm('您确定要取消吗', '提示', {
    customClass: 'custom-message-box',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    draggable: true,
  }).then(() => {
    Info('已取消保存');
    cleanAll();
    subjectVisible.value = false;
  }).catch(() => {
    //取消没有操作
  });
}
const editSubject = (id) => {
  subjectVisible.value = true;
  subjectTitle.value = '编辑信息';
  axios.get(BASE_URL + '/v1/subject/select?id=' + id)
      .then((response) => {
        if (response.data.code === 2000) {
          saveFrom.value = response.data.data[0];
          fileList.value = [{
            url: BASE_URL + saveFrom.value.poster,
            response: {
              data: saveFrom.value.poster
            }
          }]
        } else {
          ElMessage({
            message: response.data.msg,
            type: 'error',
            showClose: true,
            center: true,
          })
        }
      })
}
const deleteSubject = (id) => {
  ElMessageBox.confirm('您确定要删除吗', '提示', {
    customClass: 'custom-message-box',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    draggable: true,
  }).then(() => {
    axios.delete(BASE_URL + '/v1/subject/delete/' + id)
        .then((response) => {
          if (response.data.code === 2000) {
            OKInfo('删除成功!')
            search();
          } else {
            ElMessage({
              message: response.data.msg,
              type: 'error',
              showClose: true,
              center: true,
            })
          }
        })
    }).catch(() => {
    Info('已取消删除')
  });
}

const findAll = (id) => {
  router.push('/filmSubject?id='+id)
}
</script>

<style scoped>

</style>